package com.cloudcc.mobile.view.market;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.Bind;
import butterknife.OnClick;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.model.Jxmedel;
import com.cloudcc.cloudframe.util.GsonUtil;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.ExtraConstant;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.listbrforeadapter;
import com.cloudcc.mobile.entity.market.MarketActivityEntity;
import com.cloudcc.mobile.event.MarketActivityEventList.MarketCheckPhoneNumberEvent;
import com.cloudcc.mobile.event.MarketActivityEventList.MarketCheckResultEvent;
import com.cloudcc.mobile.event.MarketActivityEventList.MarketEventInfoEvent;
import com.cloudcc.mobile.event.MarketActivityEventList.MarketRefreshInfo;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.presenter.MarketActivityPresenter;
import com.cloudcc.mobile.util.ViewUtils;
import com.cloudcc.mobile.view.base.BaseFragment;
import com.cloudcc.mobile.widget.CloudCCTitleBar;
import com.cloudcc.mobile.widget.CloudCCTitleBar.OnTitleBarClickListener;
import com.litesuits.android.log.Log;
import com.zbar.lib.CaptureActivity;

/**
 * @Description: TODO()
 * @author wangzhiqiang
 * @date 2016-4-22 上午10:59:54
 * 
 */
public class MarketActivityInfoFragment extends BaseFragment implements
		IEventLife, OnTitleBarClickListener {
	private String mEns = RunTimeManager.getInstance().getlanguage();
	@Bind(R.id.market_et_phonenumber)
	TextView market_et_phonenumber;
	@Bind(R.id.market_tv_won)
	TextView tvWho;
	@Bind(R.id.shangyiwei)
	TextView shangyiwei;
	
	@Bind(R.id.market_tv_reqnum)
	TextView market_tv_reqnum;// 要求签到人数
	@Bind(R.id.market_tv_has_pq)
	TextView market_tv_has_pq;// 已经签到人数
	@Bind(R.id.market_btn_verification)
	Button market_btn_verification;
	@Bind(R.id.market_btn_qrcode)
	Button market_btn_qrcode;
	@Bind(R.id.headerbar)
	CloudCCTitleBar headerbar;
	@Bind(R.id.lllllsssii)
	ListView list_shangyiwei;
	// @Bind(R.id.market_checkbox1)
	// CheckBox market_checkbox1;
	// @Bind(R.id.market_checkbox2)
	// CheckBox market_checkbox2;
	// @Bind(R.id.market_checkbox3)
	// CheckBox market_checkbox3;
	// @Bind(R.id.market_checkbox4)
	// CheckBox market_checkbox4;
	// @Bind(R.id.market_checkbox5)
	// CheckBox market_checkbox5;
	// @Bind(R.id.market_checkbox6)
	// CheckBox market_checkbox6;
	// @Bind(R.id.market_checkbox7)
	// CheckBox market_checkbox7;
	// @Bind(R.id.market_checkbox8)
	// CheckBox market_checkbox8;
	// @Bind(R.id.market_checkbox9)
	// CheckBox market_checkbox9;
	// @Bind(R.id.market_checkbox10)
	// CheckBox market_checkbox10;

	// @Bind(R.id.make_phone_tv_name)
	// TextView tv_name;
	// @Bind(R.id.make_phone_tv_name_value)
	// TextView tv_name_value;
	// @Bind(R.id.make_phone_tv_phone)
	// TextView tv_phone;
	// @Bind(R.id.make_phone_tv_phone_value)
	// TextView tv_phone_value;
	// @Bind(R.id.make_phone_tv_person)
	// TextView tv_person;
	// @Bind(R.id.make_phone_tv_person_value)
	// TextView tv_person_value;
	// @Bind(R.id.make_phone_tv_jieduan)
	// TextView tv_jieduan;
	// @Bind(R.id.make_phone_tv_jieduan_value)
	// TextView tv_jieduan_value;
	// @Bind(R.id.make_phone_tv_country)
	// TextView tv_country;
	// @Bind(R.id.make_phone_tv_country_value)
	// TextView tv_country_value;
	//
	// @Bind(R.id.make_phone_tv_6)
	// TextView tv_6;
	// @Bind(R.id.make_phone_tv_6_1)
	// TextView tv_6_1;
	// @Bind(R.id.make_phone_tv_7)
	// TextView tv_7;
	// @Bind(R.id.make_phone_tv_7_1)
	// TextView tv_7_1;
	// @Bind(R.id.make_phone_tv_8)
	// TextView tv_8;
	// @Bind(R.id.make_phone_tv_8_1)
	// TextView tv_8_1;
	// @Bind(R.id.make_phone_tv_9)
	// TextView tv_9;
	// @Bind(R.id.make_phone_tv_9_1)
	// TextView tv_9_1;
	// @Bind(R.id.make_phone_tv_10)
	// TextView tv_10;
	// @Bind(R.id.make_phone_tv_10_1)
	// TextView tv_10_1;
	listbrforeadapter listbrforeadapter;
	private MarketActivityPresenter mMarketPresenter = new MarketActivityPresenter();

	private MarketActivityEntity mMarketActivityInfo;
	private String mMarketActivityId;

	@Override
	public void init() {
		initHeader();
		register();
		refreshInfoData();
	}

	/**
	 * 初始化标题
	 */
	private void initHeader() {
		String title = getArguments().getString(ExtraConstant.EXTRA_NAME, "");
		mMarketActivityId = getArguments()
				.getString(ExtraConstant.EXTRA_ID, "");
		Log.d("telephone", mMarketActivityId + "mMarketActivityId");

		headerbar.setTitle(title);
		headerbar.setOnTitleBarClickListener(this);

	}

	/**
	 * 刷新info 数据
	 */
	private void refreshInfoData() {
		if ("en".equals(mEns)) {
			showWainting("Please wait...");
			}else{
				showWainting("请稍等...");
		}
	
		headerbar.beginProgress();
		mMarketPresenter.queryMarketActivityInfo(mMarketActivityId);

	}

	@OnClick(R.id.market_btn_qrcode)
	public void onClickQrCode() {
		Intent intent = new Intent(mContext, CaptureActivity.class);
		startActivityForResult(intent, 10001);
	}

	@OnClick(R.id.market_btn_verification)
	public void onClickVerification() {// 验证 手机号码
		
		if ("en".equals(mEns)) {
			showWainting("Verifying your phone number...");
			}else{
				showWainting("正在验证手机号码...");
		}
		if (market_et_phonenumber.getText().toString().trim() == null
				|| "".equals(market_et_phonenumber.getText().toString().trim())) {
			if ("en".equals(mEns)) {
				Toast.makeText(mContext, "The phone number can not be empty", 0).show();
				}else{
					Toast.makeText(mContext, "手机号码不能为空", 0).show();
			}
			
			Log.d("phoneerror1", "手机号码空");
			dismissWainting();
		} else {
			mMarketPresenter.valPhoneNumber(market_et_phonenumber.getText()
					.toString().trim(), mMarketActivityId);
			Log.d("telephone", market_et_phonenumber.getText().toString()
					+ "是否为空 ");
			dismissWainting();
		}
	}

	public class check {
		public int checkposition;
		public boolean ischeck;
	}

	public void onEventMainThread(List<Jxmedel> jx) {
		if (listbrforeadapter == null) {
			shangyiwei.setVisibility(View.VISIBLE);
			listbrforeadapter = new listbrforeadapter(mContext, jx);
			list_shangyiwei.setAdapter(listbrforeadapter);
		}

	}

	String isyizhi;

	public void onEventMainThread(Jxmedel jx) {
		if (jx.getResult() == false) {
			String s3 = "亲，扫二维码签到失败!";
			if ("en".equals(mEns)) {
				
				 s3 = "Pro, sweep two-dimensional code sign to failure!";
				}else{
					
					 s3 = "亲，扫二维码签到失败!";
			}
			if (jx.getUrl().length() > 5) {
				QrCodeModel bean = GsonUtil.json2Bean(isyizhi,
						QrCodeModel.class);
				String s1 = "亲，成员不属于当前市场活动，是否将成员注册为该市场活动";
				String s2 = "亲，手机号码未注册，是否注册";
				
				if ("en".equals(mEns)) {
					 s1 = "Pro, members do not belong to the current market activities, whether members will be registered as the market activities";
					 s2 = "Pro, phone number is not registered, whether to register";
					}else{
						 s1 = "亲，成员不属于当前市场活动，是否将成员注册为该市场活动";
						 s2 = "亲，手机号码未注册，是否注册";
				}
				if (bean.campaignid != bean.campaignmemberid) {
					showDiaLog(jx.getUrl(), s1);
				} else {
					showDiaLog(jx.getUrl(), s2);
				}
			} else {
				Toast.makeText(mContext, s3, 0).show();
			}
		}

	}

	// 扫一扫返回
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.d("saoyisao", "扫一扫返回" + requestCode + "resultCode"
				+ (resultCode == Activity.RESULT_OK));
		if (requestCode == 10001 && resultCode == Activity.RESULT_OK) {
			String result1 = data.getStringExtra("result");
			isyizhi = result1;
			Log.d("result1", result1.toString() + "sdcsd" + data.toString());
			checkIn(result1);
		}

	}

	private class QrCodeModel {
		public String phone;
		public String campaignmemberid;
		public String campaignid;
	}

	private void checkIn(String jsonStr) {
		try {
			QrCodeModel bean = GsonUtil.json2Bean(jsonStr, QrCodeModel.class);
			if ("en".equals(mEns)) {
				showWainting("Please wait, sign in...");
				if (null == bean) {
					dismissWainting();
					showToast("Sorry, this two-dimensional code is invalid, please confirm the two-dimensional code after the re-scan！");
					return;
				}
				}else{
					showWainting("请稍等,正在签到...");
					if (null == bean) {
						dismissWainting();
						showToast("对不起，此二维码无效，请确认二维码后重新扫描！");
						return;
					}
			}
			

			mMarketPresenter.checkByQrcode(bean.campaignmemberid, bean.phone,
					mMarketActivityId);
		} catch (Exception e) {
			if ("en".equals(mEns)) {
				Toast.makeText(mContext, "Unrecognized two-dimensional code, please confirm your two-dimensional code！", 0).show();
			}else{
				Toast.makeText(mContext, "无法识别的二维码，请确认您的二维码！", 0).show();
		}
			
		}
	}

	public void onEventMainThread(MarketCheckResultEvent event) {
		dismissWainting();
		headerbar.completeProgress();
		if (event.isError()) {
			Log.d("saoyisao",
					event.getMessage() + "已经签到无需再签" + event.getMessage() != null
							+ "huozhe  " + ("".equals(event.getMessage())));
			if (event.getMessage() == null || ("".equals(event.getMessage()))) {
				// Toast.makeText(mContext,"手机号未注册" , 0).show();
			} else {

				Toast.makeText(mContext, event.getMessage(), 0).show();
			}
			// showDiaLog("111");
			return;

		}
		// 没有签到的签到成功走这里
		Log.d("saoyisao", event.getMessage() + "asedfsfsd");
		if ("en".equals(mEns)) {
			showToast("Sign in success...");
		}else{
			showToast("签到成功...");
	}
		
		// 刷新市场活动详情
		MarketRefreshInfo marketRefreshInfo = new MarketRefreshInfo();
		marketRefreshInfo.setOk(true);
		EventEngine.post(marketRefreshInfo);
	}

	public void onEventMainThread(MarketEventInfoEvent event) {
		dismissWainting();
		headerbar.completeProgress();
		if (event.isError()) {
			if ("en".equals(mEns)) {
				Toast.makeText(mContext, "Pro, get details failed~~", 0).show();
			}else{
				Toast.makeText(mContext, "亲,获取详情失败~~", 0).show();
		}
			
			getActivity().finish();
			return;
		}
		mMarketActivityInfo = event.getData().get(0);
		fillDetails();
	}

	/**
	 * 验证手机号码
	 * 
	 * @param event
	 *            2016-4-5
	 */
	public void onEventMainThread(MarketCheckPhoneNumberEvent event) {
		// Log.d("onEventMainThread1",event.getData().name+event.getData().phone+event.getData().id);
		// Log.d("onEventMainThread2","shoujhao"+event.isOk()+event.getMessage());
		// Log.d("onEventMainThread",event.isError()+"是否"+
		// "传递回来的数据"+"||"+event.getData()+"||"+"传递消息"+event.getMessage());
		Log.d("shujuwangnazou", event.isOk() + "shuju");

		headerbar.completeProgress();
		if (event.isError()) {
			Toast.makeText(mContext, event.getMessage(), 0).show();
			return;

		} else if (event.getData().getName() == null
				| "".equals(event.getData().getName())) {
			if ("en".equals(mEns)) {
				if (event.getData().getUrl().length() > 5) {
					showDiaLog(event.getData().getUrl(), "Phone number is not registered, whether to jump page to register");
					return;
				} else {
					Toast.makeText(mContext, "Pro, phone number verification failed！", 0).show();
					return;
				}
			}else{
				if (event.getData().getUrl().length() > 5) {
					showDiaLog(event.getData().getUrl(), "手机号码未注册，是否跳转页面进行注册");
					return;
				} else {
					Toast.makeText(mContext, "亲，手机号验证失败！", 0).show();
					return;
				}
		}
			
		}
		Intent intent = new Intent(mContext, MarketCheckPhoneActivity.class);
		intent.putExtra(ExtraConstant.EXTRA_ID, mMarketActivityId);
		intent.putExtra("market.phone", market_et_phonenumber.getText()
				.toString().trim());
		intent.putExtra("market.name", event.getData().name);
		startActivity(intent);
	}

	class Ddialog {
		private TextView name;
	}

	private void showDiaLog(final String url, String string) {
		// TODO Auto-generated method stub
		final Ddialog dd = new Ddialog();
		LayoutInflater inflater = getActivity().getLayoutInflater();
		View layout = inflater.inflate(R.layout.define_deleted, null);
		dd.name = (TextView) layout.findViewById(R.id.titletitle);
		dd.name.setText(string);
		final AlertDialog builder = new AlertDialog.Builder(getActivity())
				.create();
		builder.setView(layout);
		builder.show();
		Button cancle = (Button) layout.findViewById(R.id.quxiaocanle);
		cancle.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				builder.cancel();

				Log.d("getActivity", getActivity().toString());
			}
		});
		Button sure = (Button) layout.findViewById(R.id.quedingsure);
		sure.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (url == null | "".equals(url)) {
					builder.cancel();
					Log.d("builder", "url时空 并且走到了这一步");
				} else {
					Log.d("url", "urlshi" + url.substring(1, url.length() - 1));
					Uri uri = Uri.parse(url.substring(1, url.length() - 1));
					Intent it = new Intent(Intent.ACTION_VIEW, uri);
					startActivity(it);
				}

			}
		});
	}

	/**
	 * 刷新
	 * 
	 * @param event
	 *            2016-4-22
	 */
	public void onEventMainThread(MarketRefreshInfo event) {
		mMarketPresenter.queryMarketActivityInfo(mMarketActivityId);
	}

	/**
	 * 填充详情
	 */
	private void fillDetails() {
		tvWho.setVisibility(View.VISIBLE);
//		shangyiwei.setVisibility(View.VISIBLE);
		ViewUtils.setText(market_tv_reqnum,
				covertString(mMarketActivityInfo.getYqhyrs()));
		ViewUtils.setText(market_tv_has_pq,
				covertString(mMarketActivityInfo.getYqdrs()));
		if ("en".equals(mEns)) {
			ViewUtils.setText(tvWho,"Everyone:"+ String.valueOf(mMarketActivityInfo.getOwneridccname()));
		}else{
			ViewUtils.setText(tvWho,"所有人:"+ String.valueOf(mMarketActivityInfo.getOwneridccname()));
	}
		
	}

	private String covertString(String aa) {
		if (TextUtils.isEmpty(aa)) {
			return String.valueOf(0);
		}
		String remove = StringUtils.remove(aa, ".00");
		return remove;
	}

	@Override
	public void onClickLeft(View v) {
		getActivity().finish();
	}

	@Override
	public void onClickRight(View v) {

	}

	@Override
	public int getLayoutId() {
		return R.layout.marketactivity_info_frag;
	}

	@Override
	public void register() {
		EventEngine.register(this);
	}

	@Override
	public void onDestroy() {
		EventEngine.uregister(this);
		super.onDestroy();
	}

	@Override
	public void unRegister() {
		EventEngine.uregister(this);
	}
}
